package com.jl.runner;

import com.jl.JLReflect;
import com.jl.JLTuple;
import com.jl.runner.annotation.JLRunner;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 启动完成执行任务
 */
@Component
@AllArgsConstructor
public class JLCommandLineRunner implements CommandLineRunner {

    private ApplicationContext appContext;

    @Override
    @SneakyThrows
    public void run(String... args) {
        String[] beans = appContext.getBeanDefinitionNames();
        for (String bean : beans) {
            runner(appContext.getBean(bean));
        }
    }

    public void runner(Object bean) {
        Class<?> clazz = bean.getClass();
        List<JLTuple.Tuple2<Method, JLRunner>> methods = JLReflect.MethodReflect.getMethod(clazz, JLRunner.class);
        for (JLTuple.Tuple2<Method, JLRunner> methodObj : methods) {
            Method method = methodObj.getV1();
            JLRunner jlRunner = methodObj.getV2();
            Object[] value = jlRunner.value();
            Object[] param = JLReflect.MethodReflect.checkParamType(method.getParameters(), value);
            try {
                method.invoke(bean, param);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
